using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using StillDesign.PhysX;

namespace Programonica.Igramonica.Physics
{
    public class RagdollReader : ContentTypeReader<RagdollDescription>
    {
        protected override RagdollDescription Read(ContentReader input, RagdollDescription existingInstance)
        {
            var ragdollDescription = new RagdollDescription();

            List<RagdollBone> bones = ReadActors(input);

            List<JointDescription> joints = ReadJoints(input);

            ragdollDescription.Actors = bones;

            ragdollDescription.Joints = joints;

            return ragdollDescription;
        }

        private static List<RagdollBone> ReadActors(ContentReader input)
        {
            var actors = new List<RagdollBone>();

            int numActors = input.ReadInt32();

            for (int i = 0; i < numActors; i++)
            {
                var bone = new RagdollBone();

                bone.ActorDescription = new ActorDescription();

                ShapeDescription shape = null;
                
                int type = input.ReadInt32();

                switch (type)
                {
                    case 0:
                        float height = input.ReadSingle();

                        float radius = input.ReadSingle();

                        shape = new CapsuleShapeDescription(radius, height);

                        break;
                }

                bone.Id = input.ReadString();
                bone.ActorDescription.BodyDescription = new BodyDescription(input.ReadSingle());
                bone.ActorDescription.Name = input.ReadString();
                bone.ActorDescription.GlobalPose = input.ReadMatrix();

                bone.ActorDescription.Shapes.Add(shape);

                actors.Add(bone);
            }

            return actors;
        }

        private static List<JointDescription> ReadJoints(BinaryReader input)
        {
            var joints = new List<JointDescription>();

            int numJoints = input.ReadInt32();

            for (int i = 0; i < numJoints; i++)
            {
                var jointDescription = new PrismaticJointDescription();

                string actor1Id = input.ReadString();
                string actor2Id = input.ReadString();

                jointDescription.Name = input.ReadString();

                joints.Add(jointDescription);
            }

            return joints;
        }
    }
}
